package b4.net
{
	import b4.util.profile.*;
	
	import flash.display.*;
	import flash.events.*;
	import flash.net.*;
	import flash.system.ApplicationDomain;

	public class ResourceLoader extends EventDispatcher
	{
		public var appDomains:Array;
		public var urlNames:Array;
		public var urlIndex:int;
		
		public function ResourceLoader()
		{
		}
		
		public function loadResources(urlNames:Array):void
		{
			if (urlNames != null && urlNames.length > 0)
			{
				this.urlNames = urlNames;
				appDomains = new Array();
				loadResourceByIndex(0);
			} 
		}
		
		private function loadResourceByIndex(index:int):void
		{
			this.urlIndex = index;
			var loader:Loader = new Loader();
			loader.load(new URLRequest(GameProfile.URL_ResourceRoot + urlNames[index]));
			loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onResourceLoaded);
			loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, onResourceProgress);
		}
		
		private function onResourceLoaded(event:Event):void
		{
			var appDomain:ApplicationDomain = event.target.applicationDomain;
			appDomains.push(appDomain);
			urlIndex++;
			if (urlIndex < urlNames.length)
			{
				loadResourceByIndex(urlIndex);
			}
			else
			{
				dispatchEvent(event);
			}
		}
		
		private function onResourceProgress(event:ProgressEvent):void
		{
			dispatchEvent(event);
		}
		
	}
}